package com.wuqi.dev;

import java.util.Arrays;
import java.util.Random;

public class InsertSort {
    private int[] array;
    private int[] array2;

    public InsertSort() {
        array = new int[10];
        Random r = new Random();
        for (int i = 0; i < array.length; i++) {
            array[i] = r.nextInt(100);
        }
        array2 = Arrays.copyOf(array, array.length);
    }

    public void sort() {
        int x = 0, y = 0;
        for (int i = 0; i < array2.length - 1; i++) {
            for (int j = 0; j < array2.length - i - 1; j++) {
                x++;
                if (array2[j] > array2[j + 1]){
                    y++;
                    int temp  = array2[j];
                    array2[j] = array2[j + 1];
                    array2[j + 1] = temp;
                }
            }
        }
        System.out.println("比较" + x + "次");
        System.out.println("交换" + y + "次");
    }

    public void sortWithInsert() {
        int x = 0, y = 0;
        for (int i = 1; i < array.length; i++) {
            for (int j = i; j > 0 ; j--) {
                x++;
                if (array[j - 1] > array[j]){
                    y++;
                    int temp = array[j - 1];
                    array[j - 1] = array[j];
                    array[j] = temp;
                } else {
                    break;
                }
            }
        }
        System.out.println("比较" + x + "次");
        System.out.println("交换" + y + "次");
    }
    public void print1(){
        System.out.println(Arrays.toString(array));
    }

    public void print2(){
        System.out.println(Arrays.toString(array2));
    }
    public static void main(String[] args) {
        InsertSort s = new InsertSort();
        System.out.print("插入排序的原始数组:");
        s.print1();
        System.out.print("冒泡排序的原始数组:");
        s.print2();
        System.out.println("插入排序开始");
        s.sortWithInsert();
        System.out.println("冒泡排序开始");
        s.sort();
        System.out.print("排序后的数组1");
        s.print1();
        System.out.print("排序后的数组2");
        s.print2();
    }
}
